package com.zg.autoform.web;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zg.autoform.vo.HeaderConfigVo;
import com.zg.common.core.R;
import com.zg.common.core.dao.autoform.*;
import com.zg.common.web.Req;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;

/**
 * @author Zxb
 */
@RestController
@RequiredArgsConstructor
public class HeaderController {
    private final DiyFormDao formDao;
    private final DiyHeaderDao headerDao;
    private final DiyColumnDao columnDao;

    @GetMapping("/header/config/list")
    public R listHeaderConfig(String formCode) {
        if (StrUtil.isBlank(formCode)) {
            return R.error("请输入表单编码");
        }
        DiyForm form = formDao.getOne(new LambdaQueryWrapper<DiyForm>()
                .eq(DiyForm::getCode, formCode));
        String username = Req.getCurrUser().getUsername();
        List<DiyHeader> headerList = headerDao.list(new QueryWrapper<DiyHeader>()
                .lambda()
                .eq(DiyHeader::getFormCode, formCode)
                .eq(DiyHeader::getUsername, username));

        List<DiyColumn> columnList = columnDao.list(new QueryWrapper<DiyColumn>()
                .lambda()
                .eq(DiyColumn::getFormId, form.getId()));

        return R.success(Arrays.asList(headerList, columnList));
    }

    @PostMapping("/header/config/update")
    @Transactional(rollbackFor = Exception.class)
    public R updateHeaderConfig(@RequestBody HeaderConfigVo headerConfigVo) {
        String formCode = headerConfigVo.getFormCode();
        String username = Req.getCurrUser().getUsername();
        //删除原来表头配置
        headerDao.remove(new QueryWrapper<DiyHeader>()
                .lambda()
                .eq(DiyHeader::getFormCode, formCode)
                .eq(DiyHeader::getUsername, username));
        List<DiyHeader> headerList = headerConfigVo.getHeaderList();
        headerList.stream().forEach(t -> {
            t.setUsername(username);
        });
        //批量新增表头配置
        headerDao.saveBatch(headerList);
        return R.success();
    }
}
